#include "RingQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <pthread.h>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>

using namespace std;

const char* ops = "+-*/";

void* costumerRoutine(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);
    while(true)
    {
        Task t;
        rq->pop(&t);
        t();
        cout << "消费完毕：" << t.formatArg() << "result:" << t.formatRes() << endl;
    }
}

void* productorRoutine(void* args)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(args);
    while(true)
    {
        sleep(1);
        int x = rand() % 100;
        int y = rand() % 100;
        char op = ops[(x+y)%strlen(ops)];

        Task t(x,y,op);
        
        //上面的工作可以多线程同时进行，提高效率
        rq->push(t);
        std::cout << "生产完毕：" << t.formatArg() << endl;
    }
}




int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task>* rq = new RingQueue<Task>();
    
    pthread_t costumer[3];
    pthread_t productor[3];
    for(int i = 0;i<3;i++)
    {
        pthread_create(costumer+i,nullptr,costumerRoutine,rq);
        pthread_create(productor+i,nullptr,productorRoutine,rq);
    }

    for(int i = 0;i<3;i++)
    {
        pthread_join(costumer[i],nullptr);
        pthread_join(productor[i],nullptr);
    }

    delete rq;
    return 0;
}
